package cn.dbyl.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.commons.exec.ExecuteException;

public class SDKUtils {

	private String tools;
	private String platformTools;

	/**
	 * This method is for get SDK path from Environment
	 * 
	 * @since 2016/03/03
	 * @author Young
	 * @return
	 */
	public static String getAndroidHomePath() {
		String SDKPath = null;
		Map<String, String> env = System.getenv();
		for (String value : env.keySet()) {
			if (value.contains("ANDROID")) {
				SDKPath = env.get(value);
			}
		}
		return SDKPath;
	}

	/**
	 * @author Young
	 * @param boolean
	 *            isOnLine or offline
	 * @return
	 * @throws IOException
	 * @throws ExecuteException
	 */
	public static ArrayList<String> getAllDevices(boolean isOnLine) throws ExecuteException, IOException {
		ArrayList<String> temp = new ArrayList<String>();
		String[] output = ExecutorUtils.runWithoutWatchDog("adb devices").split("\n");
		for (String str : output) {
			if (!StringUtils.isEmpty(str.trim())) {
				String[] innerLine = str.split("\\s+");
				String deviceName;
				if (innerLine.length == 2) {
					if (isOnLine) {
						deviceName = StringUtils.getMatchGroup(str, "(.*)\\s+device", 1);
					} else {
						deviceName = StringUtils.getMatchGroup(str, "(.*)\\s+offline", 1);
					}

					temp.add(deviceName);
				}

			}
		}
		return temp;
	}

	/**
	 * @author Young
	 * @return
	 * @throws IOException
	 * @throws ExecuteException
	 */
	public static boolean killADB() throws ExecuteException, IOException {
		int exitCode = ExecutorUtils.runWithoutWatchDog("adb kill-server", true);
		return exitCode == 0 ? true : false;

	}

	/**
	 * @author Young
	 * @return
	 * @throws IOException
	 * @throws ExecuteException
	 */
	public static boolean startADB() throws ExecuteException, IOException {
		int exitCode = ExecutorUtils.runWithoutWatchDog("adb start-server", true);
		return exitCode == 0 ? true : false;
	}

	/**
	 * This method is for adb shell commamd
	 * 
	 * @author Young
	 * @param deviceId
	 * @param command
	 * @return
	 * @throws IOException
	 * @throws ExecuteException
	 */
	public static String ADBShell(String deviceId, String command, boolean isDebug)
			throws ExecuteException, IOException {
		String adbCommand = "adb shell";
		if (!StringUtils.isEmpty(command)) {
			adbCommand = "adb shell " + command;
		}
		if (!StringUtils.isNullOrEmpty(deviceId)) {
			adbCommand = "adb -s" + deviceId + " shell " + command;
		}
		String output = ExecutorUtils.runWithoutWatchDog(adbCommand);
		return output;
	}

	/**
	 * This method is for Execute ADB command
	 * 
	 * @param command
	 * @return
	 * @throws ExecuteException
	 * @throws IOException
	 */
	public static String ADBShell(String command) throws ExecuteException, IOException {
		return ADBShell(null, command, true);
	}
}
